<!-- 首页 -->
<template>
    <ContentWrap>
        <div class="flex justify-between">
            <div class="flex aic jcsb fontz fonts16 fontw700" style="width: 100%;margin-bottom: 20px;">
                广告位(建议尺寸：长广告位1200*120,短广告位：587*162)
                <el-button type="primary" @click="action(null)" icon="Plus">新增</el-button>
            </div>
        </div>
        
        <Table :columns="allSchemas.tableColumns" :data="state.dataList" :headerCellStyle="headerCellStyle"
            :rowStyle="rowStyle" />
        <Dialog v-model="dialogVisible2" :title="state.dialogVisible2Title">
            <el-form ref="ruleFormRef" :model="state.ruleForms" label-position="top" :rules="rules" label-width="120px"
                class="demo-ruleForm" status-icon>
                <!-- <el-form-item label="名称" prop="">
                    <el-input v-model="state.ruleForms.contentTitle" placeholder="请输入名称" disabled style="width: 350px;" />
                </el-form-item> -->
                <el-form-item label="类型" prop="contentType">
                    <el-select v-model="state.ruleForms.contentType" class="m-2" placeholder="请选择类型">
                        <el-option v-for="item in state.options" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="地址链接（英文符 ' ; ' 隔开）" prop="contentContents">
                    <el-input v-model="state.ruleForms.contentContents" placeholder="请输入地址链接用；隔开" style="width: 350px;" />
                </el-form-item>
                <el-form-item label="广告展示图" prop="picOssIds">
                    <UpLoadImages :data="state.upLoadImages" @uploadImageClick="uploadImageClicks" />
                </el-form-item>
                <el-form-item>
                    <div class="flex jcfe w-[100%]">
                        <el-button type="primary" v-loading="loadingAdd" @click="submitForms(ruleFormRef)">保存</el-button>
                        <el-button @click="resetForms(ruleFormRef)">取消</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </Dialog>
    </ContentWrap>
</template>

<script lang="tsx" setup>
import { getTreeLists} from "@/api/column/index"
import { getBaseApi, getBaselistApi, addBaseApi, putBaseApi, addsDeteleBaseApi, addsBaseApi, deteleBaseApi, getDetailApi } from "@/api/setting/index";
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { Table } from '@/components/Table'
import { Search, Refresh, Plus, Delete } from '@element-plus/icons-vue'
import { ElButton, ElInput, ElMessage, ElMessageBox } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { ref, reactive, unref, onMounted } from "vue"
import { useI18n } from '@/hooks/web/useI18n'
import { Dialog } from '@/components/Dialog'
import type { FormInstance, FormRules } from 'element-plus'
import UpLoadImages from "@/views/Components/UpLoadImages.vue"
import { useAppStoreWithOut } from '@/store/modules/app'
import { useStorage } from '@/hooks/web/useStorage'
const { getStorage } = useStorage()
const appStore = useAppStoreWithOut()
const userInfo = getStorage(appStore.getUserInfo)
const { t } = useI18n()
const loadingAdd = ref(false)
const dialogVisible2 = ref(false)
// 表格头部信息
const headerCellStyle: any = {
    "background": "#F2F6FC",
    "height": "48px"
}
// 
const rowStyle: any = {
    "height": "48px"
}
// 表格基本信息
const crudSchemas = reactive<CrudSchema[]>([
    {
        field: 'name',
        label: t('名称'),
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div>{data[0].row.contentType==0?'长广告':'短广告'}</div>

                        </>
                    )
                }
            }
        }
    },
    {
        field: 'contentContents',
        label: t('地址链接'),
    },
    {
        field: 'action',
        width: '260px',
        label: t('tableDemo.action'),
        search: {
            hidden: true
        },
        form: {
            hidden: true
        },
        detail: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <ElButton link type="primary" onClick={() => action(data[0].row)}>
                                {t('编辑')}
                            </ElButton>
                            <ElButton link type="danger" onClick={() => delData(data[0].row)}>
                                {t('删除')}
                            </ElButton>

                        </>
                    )
                }
            }
        }
    }
])
const { allSchemas } = useCrudSchemas(crudSchemas)
// ---------------------------------------state
const state = reactive({
    baseTitle:"home_ad",
    baseType:"",
    datas: [] as any,
    ruleForms: {} as any,
    dialogVisible2Title: "新增",
    upLoadImages: {
        tip: "注意:最多上传10张，单张图片大小不超过2M，支持jpg、jpeg、png格式",
        urls: [],
        ossIds: "",
        limit: 10,
        actionUrl: "/api/resource/oss/upload",
        headers: {
            "Authorization": `Bearer ${userInfo ? userInfo.access_token : ""}`,
            "clientid": userInfo ? userInfo.client_id : "e5cd7e4891bf95d1d19206ce24a7b32e"
        }
    },
    dataList: [],
    options: [
        {
            label: "长广告",
            value: 0,
        },
        {
            label: "短广告",
            value: 1,
        }
    ]
})
// ---------------------------------------图片上传
// 
const uploadImageClicks = (value: any) => {
    state.ruleForms.picOssIds = value ? value : ""
    console.log("多图片上传", state.ruleForms.picOssIds);
}
const submitForms = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (state.dialogVisible2Title == '新增') {
                state.ruleForms.baseTitle = "home_ad"
                state.ruleForms.baseType = state.baseType
                addBaseApi(state.ruleForms).then((res: any) => {
                    ElMessage({
                        type: 'success',
                        message: `${res.msg}`,
                    })
                    formEl.resetFields()
                    getBaseApiApi_()
                    dialogVisible2.value = false
                    loadingAdd.value = false
                }).catch((res: any) => {
                    ElMessage({
                        type: 'error',
                        message: `${res.msg}`,
                    })
                    loadingAdd.value = false
                })
            } else {
                putBaseApi(state.ruleForms).then((res: any) => {
                    ElMessage({
                        type: 'success',
                        message: `${res.msg}`,
                    })
                    formEl.resetFields()
                    getBaseApiApi_()
                    dialogVisible2.value = false
                    loadingAdd.value = false
                }).catch((res: any) => {
                    ElMessage({
                        type: 'error',
                        message: `${res.msg}`,
                    })
                    loadingAdd.value = false
                })

            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
const resetForms = (formEl: FormInstance | undefined) => {
    dialogVisible2.value = false
    if (!formEl) return
    formEl.resetFields()
}
const action = (row: any) => {
    if (!row) {
        state.ruleForms = {}
        state.upLoadImages.urls = []
        state.dialogVisible2Title = '新增'
        dialogVisible2.value = true;
    } else {
        console.log(row);
        dialogVisible2.value = true;
        state.ruleForms = row
        state.upLoadImages.urls = row.picOssIds ? urlFuns(row.picFiles, row.picOssIds) : []
        state.dialogVisible2Title = '编辑'
    }

}

// --------------------------------------------------
interface RuleForm {
    contentType: string
    contentContents:string
    picOssIds:string
    bigPicOssIds:string
}
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
    picOssIds: [{required: true,message: '必填项',trigger: 'blur',},],
    contentType: [{ required: true, message: '必选项', trigger: 'change' },],
    contentContents:[{ required: true, message: '必填项', trigger: 'blur' },],
    bigPicOssIds: [{required: true, message: '必填项', trigger: 'blur',},],
})

// ---------------------------------------api
const getBaseApiApi_ = async () => {
    getBaseApi({ baseTitle: "home_ad" }).then((res: any) => {
        console.log("广告位", res);
        state.dataList=res.data
    })
}
function urlFun(data) {
    let arrays = [] as any
    data.forEach(element => {
        let obj = {
            response: {
                data: {
                    ossId: element.ossId,
                    url: element.url
                }
            },
            url: element.url
        }
        arrays.push(obj)
    });
    return arrays
}
function urlFuns(data, ids) {
    let array = data
    let arrayIds = ids.split(',')
    let arrays = [] as any
    array.forEach(element => {
        let obj = {
            response: {
                data: {
                    ossId: "",
                    url: element.url
                }
            },
            url: element.url
        }
        arrays.push(obj)
    });
    arrayIds.forEach((element, key) => {
        arrays[key].response.data.ossId = element
    });
    console.log(arrays);
    return arrays


}
onMounted(() => {
    getTreeListApi()
    // getBaseApiApi_()

})
const delData = (row: any) => {
    ElMessageBox.confirm('确认删除该广告？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:,
        draggable: true,
        type: 'warning',
    }).then(() => {
        deteleBaseApi(row.id).then((res: any) => {
            getBaseApiApi_()
            ElMessage({
                type: 'success',
                message: `${res.msg}`,
            })
        }).catch((res: any) => {
            ElMessage({
                type: 'error',
                message: `${res.msg}`,
            })
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消操作',
        })
    })


}
const getTreeListApi = async()=>{
    let params={}
    getTreeLists(params).then(res=>{
        console.log("详情：",res);
        res.data.forEach(element => {
            traverseTree(element)
        });
        console.log(state.baseType);
        getBaseApiApi_()
    })
}
function traverseTree(node) {
    if(node.data.baseTitle==state.baseTitle){
        state.baseType=node.data.baseType
    }
    if (node.children && node.children.length > 0) {
        for (let child of node.children) {
            traverseTree(child); // 递归遍历子节点  
        }
    }
}
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    text-align: center;
}
</style>
<style lang="less" scoped>
.avatar-uploader .avatar {
    width: 90px;
    height: 90px;
    display: block;
}
</style>